<?php
namespace Models;

require_once('\Models\Database.php');
require_once('\Common\DBTables.php');
require_once('\Models\UserCatalog.php');
require_once('\Models\Password.php');
require_once('\Common\Strings.php');
require_once('\Common\Validator.php');

class ManageUsersModel
{
	private $_db = null;
	private $_dbt = null;
	public $errors;
	
	public function __construct(\Models\Database $db)
	{
		$this->_db = $db;
		$this->_dbt = new \Common\DBTables();
		$this->errors = array();
	}
	
	/**
	 * Skapa en användare
	 * @param $user string
	 * @param $password string
	 * @param $repeatPassword string
	 * @param $minLength integer
	 * @return $output array felmeddelanden (tom om inga felmeddelanden)
	 */
	public function createUser($userTypeId, $userName, $firstName, $lastName, $email, $password, $repeatPassword, $minLength)
	{
		$this->errors = array();
		$insertId = 0;
		
		// Ta bort HTML och JS från strängar
		$un = \Common\Validator::filterString($userName, 1);
		$un = \Common\Validator::filterString($un, 0);
		$fn = \Common\Validator::filterString($firstName, 1);
		$fn = \Common\Validator::filterString($fn, 0);
		$ln = \Common\Validator::filterString($lastName, 1);
		$ln = \Common\Validator::filterString($ln, 0);
		$em	= \Common\Validator::filterString($email, 1);
		$em	= \Common\Validator::filterString($em, 0);
			
		if(!\Common\Validator::validateNumber($userTypeId))
			$this->errors[] = \Common\Strings::VALIDATION_USERTYPE_INCORRECT;
		
		if(!\Common\Validator::validateUserName($un))
			$this->errors[] = \Common\Strings::VALIDATION_USERNAME_INCORRECT;
		
		if(!\Common\Validator::validateName($fn))
			$this->errors[] = \Common\Strings::VALIDATION_FIRSTNAME_INCORRECT;
		
		if(!\Common\Validator::validateName($ln))
			$this->errors[] = \Common\Strings::VALIDATION_LASTNAME_INCORRECT;
		
		if(!\Common\Validator::validateEmail($em))
			$this->errors[] = \Common\Strings::VALIDATION_EMAIL_INCORRECT;
		
		if(!\Common\Validator::validatePassword($password, $minLength))
			$this->errors[] = \Common\Strings::VALIDATION_PASSWORD_INCORRECT;
		
		if(!\Common\Validator::compareStrings($password, $repeatPassword))
			$this->errors[] = \Common\Strings::VALIDATION_PASSWORD_MISMATCH;
				
		// Om användarnamnet redan finns
		if ($this->_db->alreadyExists($this->_dbt->userTable,$this->_dbt->userNameField, $userName))
			$this->errors[] = \Common\Strings::DB_USER_EXISTS;
		
		// Om eposten redan finns
		if ($this->_db->alreadyExists($this->_dbt->userTable,$this->_dbt->emailField, $email))
			$this->errors[] = \Common\Strings::DB_EMAIL_EXISTS;
		
		// Hasha lösenordet innan vi sparar det i DB
		$hashedPassword = \Models\Password::hashPassword($password);
		
		// Exekvera sql om inga fel uppstått
		if(count($this->errors) == 0)
		{
			// Skapa användaren
			$sql = "INSERT INTO ".$this->_dbt->userTable.
			"(".
			$this->_dbt->userTypeIdField.",".
			$this->_dbt->userNameField.",".
			$this->_dbt->firstNameField.",".
			$this->_dbt->lastNameField.",".
			$this->_dbt->passwordField.",".
			$this->_dbt->emailField.
			") 
			VALUES (?,?,?,?,?,?)";
			
			// Infoga användaren
			$statement = $this->_db->Prepare($sql);
			$statement->bind_param("isssss", $userTypeId, $un, $fn, $ln, $hashedPassword, $em);
			$insertId = $this->_db->Insert($statement);
			
			$this->createToken($insertId);
		}
		
		return $insertId;
	}

	/**
	 * Tar bort en användare ur DB
	 * @param $loginID int
	 * @return bool
	 */
	public function deleteUser($userId = "", $userName = "")
	{
		$uc = new \Models\UserCatalog();
		
		if($userName != "")
		{
			$sql = "DELETE FROM ".$this->_dbt->userTable." WHERE ".$this->_dbt->userNameField."='$userName'";
			$statement = $this->_db->Prepare($sql);
			
			// Kollar om användarnamnet finns
			if($this->_db->alreadyExists($this->_dbt->userTable, $this->_dbt->userNameField, $userName))
				return $this->_db->Delete($statement);
		}
		else if($userId != "")
		{
			$sql = "DELETE FROM ".$this->_dbt->userTable." WHERE ".$this->_dbt->userIdField."='$userId'";
			$statement = $this->_db->Prepare($sql);
			
			// Kollar om användar-id finns
			if($this->_db->alreadyExists($this->_dbt->userTable, $this->_dbt->userIdField, $userId))
				return $this->_db->Delete($statement);
		}
		else
			return false;
	}
	
	private function createToken($userId)
	{
		// Skapa en token för användare
		$sql = "INSERT INTO ".$this->_dbt->tokenTable.
		"(".
		$this->_dbt->userIdField.",".
		$this->_dbt->tokenField.",".
		$this->_dbt->ipField.
		") 
		VALUES (?,?,?)";
	
		// Infoga token
		$token = $this->generateToken(20);
		$ip = $_SERVER["REMOTE_ADDR"];
		
		$statement = $this->_db->Prepare($sql);
		$statement->bind_param("iss", $userId, $token, $ip);
		
		return $this->_db->Insert($statement);
	}
	
	public function updateToken($tokenId, $ip)
	{
		// Skapa en token för användare
		$sql = "UPDATE ".$this->_dbt->tokenTable." 
		SET ".$this->_dbt->ipField."=? 
		WHERE ".$this->_dbt->tokenIdField."=?";
	
		// Uppdatera token
		$statement = $this->_db->Prepare($sql);
		$statement->bind_param("si", $ip, $tokenId);
		
		return $this->_db->Update($statement);
	}
	
	/**
	 * Generera unik token
	 * @param $length int - längd på strängen
	 * @return string
	 */
	public function generateToken($length)
	{
		return substr(uniqid(), 0, $length);
	}
}

?>